<template>
  
  <div class="employees-container">
   
    <div class="app-container">
      
      <page-tools>
        
        <template #left>
           <span>总记录数: {{total}} 条</span> 
        </template>
 
        <template #right>
         
          <el-button type="warning" size="small" @click="$router.push('/upload')">excel导入</el-button> 
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button> 
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button> 
        </template>
        
      </page-tools>

      
      <el-card style="margin-top: 10px">
   
        <el-table border :data="list"  :default-sort = "{prop: 'timeOfEntry', order: 'descending'}">
   <el-table-column label="序号" type="index" /> 
          <el-table-column label="姓名" prop="username" /> 
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" /> 
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment)}}
            </template>
            </el-table-column> 
          <el-table-column label="部门" prop="departmentName" /> 
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
      
          <el-table-column label="操作" width="280">
   
            <template #default="{row}">
              
              <!-- <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)">查看</el-button>  -->
              <el-button type="text" size="small" @click="$router.push(`/detail?id=${row.id}`)">查看</el-button> 
              <el-button type="text" size="small" @click="resetShowDialog=true">分配角色</el-button> 
             <el-button type="text" size="small" @click="hDele(row.id)">删除</el-button> 
             
            </template>
       
          </el-table-column>
          
        </el-table>
     <!-- 弹框  新增员工-->
      <el-dialog title="新增员工" @close="reset"  :visible.sync="showDialog">
        <addEmployees @close="showDialog=false" ref="addEmployees" @success="hSuccess"></addEmployees>
      </el-dialog>

      <!-- 弹框  分配  -->
      <el-dialog title="分配角色"  :visible.sync="resetShowDialog">
        <assignRole @close="resetShowDialog=false"></assignRole>
      </el-dialog>
        <!-- 分页组件 -->
       
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[1, 7, 3, 10]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
        </el-row>
       
      </el-card>
   
    </div>
   
  </div>
</template>

<script>
import { getEmployees,delEmployee } from "@/api/empioyees";
import addEmployees from "@/views/employees/empDialog";
import  Employment  from "@/constant/employees";
import  assignRole  from "@/views/employees/assignRole";


const hire = {}
Employment.hireType.forEach(item=> {
  hire[item.id]=item.value
})
// Employment.hireType.reduce((ass,item)=>{
//   hire[item.id]=item.value
//   return ass
// },{})
export default {
  components:{
addEmployees,assignRole
  },
  data() {
    return {
      resetShowDialog:false,
      page: 1,
      size: 3, // 员工列表
      list: [],
      total:0,
      showDialog:false,//显示隐藏
    };
  },
  created() {
    this.loadEmployees();
  },
  methods: {
    // 导入
      formData(list) {
            const map = {
                'id': '编号',
                'password': '密码',
                'mobile': '手机号',
                'username': '姓名',
                'timeOfEntry': '入职日期',
                'formOfEmployment': '聘用形式',
                'correctionTime': '转正日期',
                'workNumber': '工号',
                'departmentName': '部门',
                'staffPhoto': '头像地址'
            }

            const one = list[0]
            if(!one) return
            const header = Object.keys(one).map(enkey =>{
                return map[enkey]
            })
            const data = list.map(item=>{
              const key = item.formOfEmployment
              item['formOfEmployment']=hire[key]||'未知'
                return Object.values(item)
            })
            return  {header:header,data:data}
        },
     
    // 批量导入
   async handleDownload() {
      try {
        const res = await getEmployees(this.page, this.size);

        const {header,data} = this.formData(res.data.rows)

        import('@/vendor/Export2Excel').then(excel => {
         
          excel.export_json_to_excel({
            header: header,
            data:data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
            
          })
          
        })
        } catch (error) {
        console.log(error);
      }
                  
    },
    // 删除
    hDele(id){
      //  console.log(id)
      this.$confirm('确认删除吗？').then(async() => {
        await delEmployee(id)
        if(this.list.length===1){
          this.page--
          if(this.page<=0){
            this.page=1
          }
        }
        this.loadEmployees()  
      }).catch(() => {})
    },
   
    // 渲染
    hSuccess(){
      this.total++
      const  maxPage = Math.ceil(this.total/this.size)
      this.page=maxPage
      this.loadEmployees()
      this.showDialog=false
    },
     // 重置
    reset(){
      // this.$refs.addEmployees.resets()
    },
    // 分页
     handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.page=1
        this.size=val
        this.loadEmployees()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.page=val
        this.loadEmployees()
      },
    // 格式化聘用形式函数
    formOfEmploymentFormat(data){
      // 返回格式化数据  正式||非正式
      // return Employment.hireType.find(item=>item.id===data).value
      return  hire[data] || '未知'
    },
    // 获取员工列表
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size);
        console.log(res); // 保存到data函数中
        this.list = res.data.rows;
        this.total=res.data.total
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>